
package com.uuah.server.bootstrap.wrapper;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.tanukisoftware.wrapper.WrapperManager;
import org.tanukisoftware.wrapper.WrapperSimpleApp;

import com.uuah.server.util.UuahBootstrapUtils;


public class UuahBootstrap {
	private static final String UUAH_MODULE_BOOT_POM_FILE_PATH = "META-INF/maven/com.uuah.server/server-core/pom.properties";

	public static final String CLI_OPTIONS[][] = { { "main", "true",
			"Main Class" } };

	public static void main(String[] args) throws Exception {
		CommandLine commandLine = parseCommandLine(args);
		String[] remainingArgs = commandLine.getArgs();

		String mainClassName = commandLine.getOptionValue("main");
		if (mainClassName == null
				|| mainClassName.equals(UuahServerWrapper.class.getName())) {
			prepareBootstrapPhase();
			System.out.println("Starting the Uuah App Server...");
			WrapperManager.start(new UuahServerWrapper(), remainingArgs);
		} else {
			String[] appArgs = new String[remainingArgs.length + 1];
			appArgs[0] = mainClassName;
			System
					.arraycopy(remainingArgs, 0, appArgs, 1,
							remainingArgs.length);
			prepareBootstrapPhase();
			System.out.println("Starting class " + mainClassName + "...");
			WrapperSimpleApp.main(appArgs);
		}
	}

	private static void prepareBootstrapPhase() throws Exception {
		prepareBootstrapPhase(true);
	}

	private static void prepareBootstrapPhase(boolean setupClassLoader)
			throws Exception {
		File uuahHome = lookupUuahServerHome();
		File uuahBase = lookupUuahBase();

		if (uuahBase == null) {
			uuahBase = uuahHome;
		}

		if (setupClassLoader) {
			UuahBootstrapUtils.addLocalJarFilesToClasspath(uuahHome, uuahBase);
		}

		setSystemUuahVersion();

	}

	private static File lookupUuahServerHome() throws Exception {
		File uuahHome = null;
		String uuahHomeVar = System.getProperty("uuah.home");

		if (uuahHomeVar != null && !uuahHomeVar.trim().equals("")
				&& !uuahHomeVar.equals("%UUAH_HOME%")) {
			uuahHome = new File(uuahHomeVar).getCanonicalFile();
		}

		if (uuahHome == null || !uuahHome.exists() || !uuahHome.isDirectory()) {
			throw new IllegalArgumentException(
					"Either UUAH_HOME is not set or does not contain a valid directory.");
		}
		return uuahHome;
	}

	private static File lookupUuahBase() throws Exception {
		File uuahBase = null;
		String uuahBaseVar = System.getProperty("uuah.base");

		if (uuahBaseVar != null && !uuahBaseVar.trim().equals("")
				&& !uuahBaseVar.equals("%UUAH_BASE%")) {
			uuahBase = new File(uuahBaseVar).getCanonicalFile();
		}
		return uuahBase;
	}

	private static void setSystemUuahVersion() {
		try {
			URL mavenPropertiesUrl = UuahBootstrapUtils.getResource(
					UUAH_MODULE_BOOT_POM_FILE_PATH, UuahServerWrapper.class);

			Properties mavenProperties = new Properties();
			mavenProperties.load(mavenPropertiesUrl.openStream());

			System.setProperty("uuah.version", mavenProperties
					.getProperty("version"));
			System.setProperty("uuah.reference.version", mavenProperties
					.getProperty("version")
					+ '-' + (new Date()).getTime());
		} catch (Exception ignore) {
			// ignore;
		}
	}

	private static CommandLine parseCommandLine(String[] args)
			throws ParseException {
		Options options = new Options();
		for (int i = 0; i < CLI_OPTIONS.length; i++) {
			options.addOption(CLI_OPTIONS[i][0], "true"
					.equalsIgnoreCase(CLI_OPTIONS[i][1]), CLI_OPTIONS[i][2]);
		}
		return new BasicParser().parse(options, args, true);
	}
}
